﻿/* 
 * 
 * Copyright 2013 Bendsoft. All rights reserved.
 * http://www.bendsoft.com
 * 
 * This code is distributed under the New BSD License (BSD).
 * 
 * @package     Camelot SharePoint Integration Plugins Library
 * @codeplex    http://camelottoolkit.codeplex.com
 * @license     New BSD License (BSD)
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Camelot.SharePointIntegration.IntegrationService;
using Camelot.SharePointIntegration.IntegrationService.Entities;
using Camelot.SharePointIntegration.Client;


namespace Camelot.SharePointIntegration.Plugins
{
    public class LibraryToDisk : DocumentLibraryDataPlugin
    {
        protected override ServicePluginResult ProcessData(Task task, DocumentLibraryData data, List<Parameter> parameters)
        {
            string folder = (from p in parameters where p.Name.ToLower() == "folder" select p.Value).FirstOrDefault();
            string maxFileSize = (from p in parameters where p.Name.ToLower() == "maxfilesize" select p.Value).FirstOrDefault();

            if (String.IsNullOrEmpty(folder))
                return new IntegrationService.ServicePluginResult() { Message = "Parameter null or empty: folder" };

            if (!folder.EndsWith("\\"))
                folder += "\\";

            if (!Directory.Exists(folder))
                return new IntegrationService.ServicePluginResult() { Message = "The folder does not exist" };

            int maxFileSizeInt = 0;
            if (!String.IsNullOrEmpty(maxFileSize) && !int.TryParse(maxFileSize, out maxFileSizeInt))
                return new IntegrationService.ServicePluginResult() { Message = "Parameter value is incorrect: maxfilesize" };

            using (var connection = new Camelot.SharePointConnector.Data.SharePointConnection(task.Command.ConnectionString))
            {
                connection.Open();
                foreach (var doc in data.Documents)
                {
                    if (doc.ContentType == "Folder")
                        if (!Directory.Exists(folder + doc.Url))
                            Directory.CreateDirectory(folder + doc.Url);

                    if (doc.ContentType != "Folder" && (maxFileSizeInt == 0 || maxFileSizeInt >= doc.FileSize))
                    {
                        if (File.Exists(folder + doc.Url))
                            if (File.GetLastWriteTime(folder + doc.Url) == doc.Modified)
                                continue;

                        using (var command = new Camelot.SharePointConnector.Data.SharePointCommand(string.Format("CALL DOWNLOAD('{0}', '{1}')", task.Command.ListName, doc.ProcedureUrl), connection))
                        {
                            byte[] fileBytes = (byte[])command.ExecuteScalar();
                            if (fileBytes != null && fileBytes.Length > 0)
                            {
                                File.WriteAllBytes(folder + doc.Url, fileBytes);
                                File.SetCreationTime(folder + doc.Url, doc.Created);
                                File.SetLastWriteTime(folder + doc.Url, doc.Modified);
                            }
                        }
                    }
                }
            }

            return new IntegrationService.ServicePluginResult() { Success = true };
        }
    }
}
